package org.base.shiro.modules.auth;


import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import lombok.Getter;
import lombok.Setter;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.base.common.R;
import org.base.common.SysException;

import static org.base.common.ResponseCode.*;
import org.base.shiro.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class LoginController {
	@Autowired
	private Producer producer;
	
	@RequestMapping("/captcha.jpg")
	public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public R login(@RequestBody LoginVO loginVO) {
		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!kaptcha.equalsIgnoreCase(loginVO.getCaptcha())){
			return new R(CAPTCHA_WRONG);
		}
		
		try{
			Subject subject = ShiroUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(loginVO.getUsername(), loginVO.getPassword());
			subject.login(token);
		}catch (UnknownAccountException|IncorrectCredentialsException e) {
			return new R(USER_PASSWORD_WRONG);
		}catch (LockedAccountException e) {
			return R.error("账号已被锁定,请联系管理员");
		}catch (SysException e) {
			return R.error(e);
		}catch (Exception e) {
			return R.error("登录失败");
		}
	    return R.ok();
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login";
	}
	
	@Setter
	@Getter
	public static class LoginVO{
		private String username;
		private String password; 
		private String captcha;
	}
	
}
